from django.shortcuts import render

from django.http import HttpResponse,JsonResponse,Http404

from .. models import Users

from web.settings import BASE_DIR

import time,os,random
from django.contrib.auth.decorators import permission_required




#会员添加


@permission_required('myadmin.insert_users',raise_exception=True)

def add(request):
    return render(request,'admin/user/add.html')

#执行添加

@permission_required('myadmin.insert_users',raise_exception=True)
def insert(request):
    #获取上传的文件
    myfile = request.FILES.get('pic',None)

    #先判断是否有文件上传

    if not myfile:
        # pic = 'default.jpg'
        pic = '/static/pics/users.jpeg'

    else:
        pic = uploads(myfile)
        if not pic:
            return HttpResponse('<script>alert("上传的文件类型错误,只能选择图片类型")</script>')
    #获取其他数据并删除csrf
    data = request.POST.dict()

    del data['csrfmiddlewaretoken']
    data['pic'] = pic

    #进行密码加密
    from django.contrib.auth.hashers import make_password, check_password
    data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')


    #执行添加
    ob = Users.objects.create(**data)
    if ob:
        return HttpResponse('<script>alert("会员添加成功");location.href="/admin/user/index/"</script>')
    else:
        return HttpResponse('<script>alert("会员添加失败");history.back(-1)"</script>')



@permission_required('myadmin.show_users',raise_exception=True)

def index(request):

    #查询所有
    obs = Users.objects.filter()

    #获取搜索类型

    types = request.GET.get('type',None)
    if types:
        #获取搜索的关键字
        keywords = request.GET.get('keywords',None)

        #判断是否是性别
        if types == 'sex':
            sexlist = {'男':'1','女':'0'}

            obs = obs.filter(sex=sexlist[keywords])

        else:
            data = {types+'__contains':keywords}

            obs = obs.filter(**data)

    #获取当前页的页数
    pageindex = request.GET.get('p',1)

    from django.core.paginator import Paginator

    #实例化分页对象

    p = Paginator(obs,5)

    obs = p.page(pageindex)



    #分配数据
    con = {'aa':obs}
    #加载模板
    return render(request,'admin/user/index.html',con)
#会员删除
@permission_required('myadmin.del_users',raise_exception=True)
def delete(request):
        
    #判断请求方式
    if request.is_ajax():
        try:
            ob = Users.objects.get(id=request.GET['id'])
            ob.isDelete = True
            ob.save()
            return JsonResponse({'code':1,'msg':'删除成功'})
        except:
            return JsonResponse({'code':0,'msg':'删除失败'})
    else:
        # 返回一个404的错误页面
        raise Http404("Poll does not exist")

@permission_required('myadmin.edit_users',raise_exception=True)   
def edit(request,uid):
    #查询行对应id数据 【object 】 object
    ob = Users.objects.get(id=uid)

    #分配数据

    con = {'hh':ob}


    #判断请求方式
    if request.method == 'GET':

        return render(request,'admin/user/edit.html',con)

    elif request.method == 'POST':

        
        #执行修改

        ob.username = request.POST['username']
        ob.email = request.POST['email']
        ob.age = request.POST['age']
        ob.phone = request.POST['phone']
        ob.sex = request.POST['sex']

        #判断是否更新了头像
        myfile = request.FILES.get('pic',None)
        if myfile:
                #判断是否时默认头像，如果不是则删除
            if ob.pic != '/static/pics/users.jpeg':
                #删除原有头像
                os.remove(BASE_DIR+ob.pic)
            ob.pic = uploads(myfile)



        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="/admin/user/index/"</script>')










def uploads(myfile):
    
    from web.settings import BASE_DIR
    import time,random,os

    # 获取文件的后缀名
    h = myfile.name.split('.').pop()
    arr = ['jpg','png','gif','jpeg']
    # 判断上传的文件类型
    if h not in arr:
        return False
    

    # 重新定义新的文件名 时间搓+随机数
    filename = str(time.time())+str(random.random())+'.'+h

    # 执行文件上传
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")

    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()

    # 返回文件路径和文件名
    return '/static/pics/'+filename





